<template>
    <div id="user-index">
        <top-nav :title="title">
            <template v-slot:right class="vist-sti">
                <span class="vist-sti-icon iconfont icon-liulan"></span>
                <span class="vist-sti-count">{{user.viewPageCount}}</span>
            </template>
        </top-nav>
        <top 
        ref="top"
        :userInfo="user"
        @setCancelFollow="setCancelFollow"
        @setFollow="setFollow"
        />
        <opt-select-sti
        ref="optSelectSti"
        :listOption="listOption" 
        :activeListOpt="activeListOpt"
        :listOptSti="listOptSti"
        @chooseOpt="chooseOpt"
        />
        <list 
        :height="height" 
        :listOption="listOption" 
        :activeListOpt="activeListOpt"
        ref="list"
        @setListData="setListData"
        @setAsStatistics="setAsStatistics"
        @setWorkshopStatistics="setWorkshopStatistics"
        @cachePageData="cachePageData"
        @setWechatStatistics="setWechatStatistics"
        />
        <user-menu ref="userMenu" :userInfo="user" />
    </div>
</template>

<script>
// 自定义组件
import TopNav from "_components/project/common/TopNav"
import Top from '_components/project/UserIndex/Top'
import UserMenu from '_components/project/UserIndex/UserMenu'
import List from '_components/project/UserIndex/List'
import OptSelectSti from '_components/project/UserIndex/OptSelectSti'

// 自定义方法
import { checkDataEqualVal } from "_commonFn/check"
import { customShare } from "_commonFn/share"
import { getUserIndex } from "_network/request"
import { failTextVantToa, loadingVantToa, clearVantToa } from "_projectFn/prompt"
import { getText } from "_commonFn/string"
import { setStatusFromStartEndTime, returnMothDay, returnWeekText, returnTimeHourMin } from "_commonFn/time"
import { checkCacheaIsPageData } from "_projectFn/check"

// 字体
import '_assets/fonts/iconfont.css'

// Vue
import Vue from 'vue'

export default {
    name: 'UserIndex',
    data() {
        return {
            title: '个人主页',
            listOption: {
                association: {
                    name: '社群',
                    id: 'association',
                    list: [],
                },
                wechat: {
                    name: '微信群',
                    id: 'wechat',
                    list: [],
                },
                workshop: {
                    name: '主讲',
                    id: 'workshop',
                    list: [],
                },
            },
            listOptSti: {
                association: '',
                workshop: '',
                wechat: '',
            },
            activeListOpt: 'association',
            user: {
                width: 60,
                height: 60,
                userId: '',
                headImg: '',
                signature: '',
                sex: null,
                isFollow: null,
                offer: null, // float	贡献分
                address: null, // string	地理位置
                isUserBusiness: null, // int	查看用户是否填写了业务信息(0:否,1:是)
                isViewWechat: null, // int	查看用户微信查看权限是否受限(0:否,1:是，-1：未知)
                isMyWx: null, // int	查看用户是否具有查看我的微信权限(0:否,1:是)
                isPayViewWx: null, // int	当前登录用户是否已支付查看过该微信(0:否,1:是)
                viewFreeWx: null, // int	当前登录用户当天免费查看我的微信次数
                maxViewFreeWx: null, // int	每个用户当天免费查看我的微信最大次数
                viewFreeWxPay: null, // float	查看用户查看我的微信支付积分
                bindUserBusiness: null, // int	被查看用户是否填写了业务信息(0:否,1:是)
                excellentaAnswer: null, // int	优答数量
                refined: null, // int	精索数量
                highTalk: null, // int	高讲数量
                appiont: null, // int	群委数量
                fans: null, // int	粉丝数量
                viewPageCount: null, // int	页面浏览次数
                loginBindWx: null, // int	当前登录用户是否已绑定微信(1:是,0:否)
                userLevel: 0,
            },
            height: 300,
            canClear: true,
        }
    },
    methods: {
        // 缓存页面数据
        cachePageData() {
            const listMescrollFig = this.$refs.list.getAllMesConfig()
            const data = {
                title: this.title,
                listOption: this.listOption,
                listOptSti: this.listOptSti,
                activeListOpt: this.activeListOpt,
                user: this.user,
                height: this.height,
                listMescrollFig,
                queryStr: this.$route.query,
                scrollTop: document.getElementById(this.activeListOpt).scrollTop,
            }
            // console.log('data', data)
            sessionStorage.setItem('UserIndexListCache', JSON.stringify(data))
        },
        // 设置页面数据
        setPageCacheData(data) {
            console.log('setPageCacheData', data)
            // this.title = data.title
            this.$refs.list.setAllMesConfig(data.listMescrollFig)
            this.listOption = data.listOption
            this.listOptSti = data.listOptSti
            this.activeListOpt = data.activeListOpt
            this.user = data.user
            this.height = data.height
            Vue.nextTick()
            .then(function () {
                document.getElementById(data.activeListOpt).scrollTop = data.scrollTop
            })
        },
        chooseOpt(opt) {
            this.activeListOpt = opt
        },
        setListData(list, option) {
            // console.log('list', list)
            // console.log('option', option)
            if (Array.isArray(list) && option) {
                const optList = this.listOption[option].list
                if (option === 'association') {
                    list.forEach(item => {
                        optList.push({
                            no: item.No, //	string	社群编号
                            groupName: item.GroupName, // string	社群名称
                            prestige: item.Prestige, // string	是否设置了人气(1:是,0:否)
                            groupType: item.GroupType, // string	群的类别或业务对象
                            area: item.Area, // string	群所属区域
                            assType: item.AssType, // string	社群类型:HY：行业群,CP:产品群,ZH:展会群，QY：区域群
                            headImg: item.HeadImg, // string	社群头像，如无则为空
                            peopleCount: item.PeopleCount, // int	群员数量
                            discussCount: item.DiscussCount, // int	群讨论数量
                            user: {
                                userId: item.UserId, // string	用户编号
                                nickName: item.NickName, // string	昵称
                                sex: item.Sex, // int	性别(1:男，2：女，-1：未知)
                                headImg: item.HeadImg, // string	用户头像
                                userLevel: item.UserLevel, // int	用户级别(0：普通用户,1:高级用户,2:资深用户,3:超级用户)
                                signature: item.Signature, // string	用户签名
                                offer: item.Offer, // Decimal	用户当前总贡献分
                            }
                        })
                    })
                } else if (option === 'workshop') {
                    const notStartObj = { // 未开始
                        className: 'enter-workshop-status-not-started',
                        firstText: '还有',
                        count: '',
                        unit: '',
                        unitText: ''
                    },
                    soonStartObj = { // 快开始
                        className: 'enter-workshop-status-quickly-started',
                        firstText: '还有',
                        count: '',
                        unit: '',
                        unitText: ''
                    },
                    underwayObj = { // 进行中
                        className: 'enter-workshop-status-ongoing',
                        firstText: '进行中',
                        count: '',
                        unit: '',
                        unitText: ''
                    },
                    endStatusObj = { // 已结束
                        className: 'workshop-list-li-status-end',
                        firstText: '已结束',
                        count: '',
                        unit: '',
                        unitText: ''
                    };
                    let statusObj = null
                    let startTime = null
                    let endTime = null
                    const nowTimeStamp = new Date().getTime();
                    list.forEach(item => {
                        startTime = Number(item.StarTime)
                        endTime = Number(item.EndTime)
                        statusObj = item.EndStatus > 0 ? endStatusObj : setStatusFromStartEndTime({nowTime: nowTimeStamp, startTime, endTime, notStartObj, soonStartObj, underwayObj, endStatusObj})
                        optList.push({
                            seminarNo: item.SeminarNo, // string	研讨会编号
                            groupNo: item.GroupNo, // string	社群编号
                            groupName: item.GroupName, // string	群名称
                            prestige: item.Prestige, // int	社群是否设置了人气,1:是,0:否
                            seminarTitle: getText(item.SeminarTitle), // string	主讲主题
                            city: item.City, // string	定位
                            seminarPlace: item.SeminarPlace, // int	主讲场所(1:微信群,2:千聊)
                            starTime: item.StarTime, // long	主讲开始时间戳
                            eandTime: item.EndTime, // long	主讲结束时间戳
                            addTime: item.AddTime, // long	主讲发布时间戳
                            updateTime: item.UpdateTime, // long	主讲更新时间戳
                            editTime: item.EditTime, // long	主讲编辑时间戳
                            viewCount: item.ViewCount, // int	浏览次数
                            endStatus: item.EndStatus, // int	结束状态：0:未结束,1:已结束,2:强制结束
                            checkStatus: item.CheckStatus, // int	审核状态：0:未审核,1:审核通过,2:审核不通过
                            isAppoint: item.IsAppoint, // int	发布用户是否是该主讲所属社群的群委(0:否,1:是)
                            statusText: statusObj.firstText + statusObj.count + statusObj.unitText,
                            startText: returnMothDay(startTime) + `(${returnWeekText({timestamp: startTime, prefixText: '星期'})})`,
                            endText: `${returnTimeHourMin(startTime)}~${returnTimeHourMin(endTime)}`,
                            className: statusObj.className,
                            user: {
                                userId: item.UsersItem.UserId, // string	用户编号
                                nickName: item.UsersItem.NickName, // string	昵称
                                sex: item.UsersItem.Sex, // int	性别(1:男，0：女，-1：未知)
                                headImg: item.UsersItem.HeadImg, // string	用户头像
                                userLevel: item.UsersItem.UserLevel, // int	用户级别(0：普通用户,1:高级用户,2:资深用户,3:超级用户)
                                signature: item.UsersItem.Signature, // string	用户签名
                                offer: item.UsersItem.Offer, // Decimal	用户当前总贡献分
                            }
                        })
                    })
                } else {
                    list.forEach(item => {
                        optList.push({
                            assNo: item.AssNo, // string	关联编号
                            wechatGroupName: item.WechatGroupName, // string	微信群名称
                            introduction: item.Introduction, // string	微信群介绍
                            introductionText: getText(item.Introduction),
                            groupNo: item.GroupNo, // string	所在社群编号
                            groupName: item.GroupName, // string	所在社群名称
                            viewCount: item.ViewCount || 0, // int	浏览次数
                            user: {
                                userId: item.UsersItem.UserId, // string	用户编号
                                nickName: item.UsersItem.NickName, // string	昵称
                                sex: item.UsersItem.Sex == 2 ? 0 : item.UsersItem.Sex, // int	性别(1:男，2：女，-1：未知)
                                headImg: item.UsersItem.HeadImg, // string	用户头像
                                userLevel: item.UsersItem.UserLevel, // int	用户级别(0：普通用户,1:高级用户,2:资深用户,3:超级用户)
                                signature: item.UsersItem.Signature, // string	用户签名
                                offer: item.UsersItem.Offer, // Decimal	用户当前总贡献分
                            }
                        })
                    })
                }
            }
        },
        setAsStatistics(data) {
            const joinCount = data.JoinCount || 0, // int	加入社群数量
            areaCount = data.QYCount || 0, // int	区域社群数量
            tradeCount = data.HYCount || 0, // int	行业社群数量
            productCount = data.CPCount || 0, // int	产品社群数量
            comCount = data.COCount || 0, // 企业群数量
            exhibitionCount = data.ZHCount || 0; // int	展会社群数量
            this.listOptSti.association = `${joinCount}个社群,区域${areaCount}个,行业${tradeCount}个,产品${productCount}个,展会${exhibitionCount}个,企业${comCount}个`
        },
        setWorkshopStatistics(data) {
            this.listOptSti.workshop = `主讲${data.SeminarCount || 0}次`
        },
        setWechatStatistics(res) {
            this.listOptSti.wechat = `外联微信群${res.total || 0}个`
        },
        // 获取本页所需数据
        getData() {
            // console.log('this.$route.query', this.$route.query)
            if (this.$route.query.userId) {
                loadingVantToa({})
                getUserIndex(this.$route.query.userId)
                .then(res => {
					console.log("获取用户的信息 res：", res)
					if (res.errcode == 0) {
                        this.setUserInfo(res.data)
                        this.setHeight()
                        this.checkShare()
                        clearVantToa()
					} else {
						failTextVantToa(res.message)
					}
				}, res => {
					console.log("fail: res", res)
					if (res.errcode != 2000) {
						failTextVantToa("服务器正在修整，请稍后")
					}
				})
				.catch(res => {
					console.log("catch：res", res)
					failTextVantToa("服务器正在修整，请稍后")
				})
            } else {
                failTextVantToa("URL地址有误")
            }
        },
        setUserInfo(data) {
            // console.log('data', data)
            if (data.UserItem) {
                // this.title = data.UserItem.NickName
                this.user.userId = data.UserItem.UserId
                this.user.name = data.UserItem.NickName
                this.user.headImg = data.UserItem.HeadImg 
                this.user.signature = data.UserItem.Signature
                this.user.userLevel = data.UserItem.UserLevel
                this.user.sex = data.UserItem.Sex == 2 ? 0 : 1
            }
            this.user.offer = data.Offer // float	贡献分
            this.user.isFollow = data.IsFuns // int 是否关注(0:否,1：是)
            this.user.address = data.Address // string	地理位置
            this.user.isUserBusiness = data.IsUserBusiness // int	查看用户是否填写了业务信息(0:否,1:是)
            this.user.isViewWechat = data.IsViewWechat // int	查看用户微信查看权限是否受限(0:否,1:是，-1：未知)
            this.user.isMyWx = data.IsMyWx // int	查看用户是否具有查看我的微信权限(0:否,1:是)
            this.user.isPayViewWx = data.IsPayViewWx // int	当前登录用户是否已支付查看过该微信(0:否,1:是)
            this.user.viewFreeWx = data.ViewFreeWx // int	当前登录用户当天免费查看我的微信次数
            this.user.maxViewFreeWx = data.MaxViewFreeWx // int	每个用户当天免费查看我的微信最大次数
            this.user.viewFreeWxPay = data.ViewFreeWxPay // float	查看用户查看我的微信支付积分
            this.user.bindUserBusiness = data.BindUserBusiness // int	被查看用户是否填写了业务信息(0:否,1:是)
            this.user.excellentaAnswer = data.ExcellentaAnswer // int	优答数量
            this.user.refined = data.Refined // int	精索数量
            this.user.highTalk = data.HighTalk // int	高讲数量
            this.user.appiont = data.Appiont // int	群委数量
            this.user.fans = Number(data.Fans) // int	粉丝数量
            this.user.viewPageCount = data.ViewPageCount // int	页面浏览次数
            this.user.loginBindWx = data.LoginBindWx // int	当前登录用户是否已绑定微信(1:是,0:否)
        },
        setCancelFollow() {
            if (this.user.fans > 0) {
                this.user.fans -= 1
            } else {
                this.user.fans = 0
            }
            this.user.isFollow = 0
        },
        setFollow() {
            this.user.fans += 1
            this.user.isFollow = 1
        },
        getComHei(el) {
            return Number(window.getComputedStyle(el).height.replace('px', ''))
        },
        setHeight() {
            this.$nextTick()
            .then(() => {
                const bodyHei = window.innerHeight || document.documentElement.clientHeight
                const topHei = this.getComHei(this.$refs.top.$el)
                const optSelectStiHei = this.getComHei(this.$refs.optSelectSti.$el)
                const userMenuHei = this.getComHei(this.$refs.userMenu.$el)
                this.height = bodyHei - 40 - topHei - userMenuHei - optSelectStiHei
            })
        },
        checkClear() {
            if (this.canClear) {
                this.clearData()
            }
        },
        clearData() {
            const that = this
            Object.keys(this.listOption).forEach(item => {
                that.listOption[item].list = []
            })
            Object.keys(this.listOptSti).forEach(item => {
                that.listOptSti[item] = ''
            })
            this.activeListOpt = 'association'
        },
        // 检测是否可以分享
        checkShare() {
            const that = this
            if (that.$store.getters.isWechatBro) {
                checkDataEqualVal({
                    data: that.$store.getters,
                    key: 'getWechatStatus',
                    val: ['success', 'fail'],
                    callback(val) {
                        if (val === 'success') {
                            // defaultShare({})
                            that.share()
                        }
                    }
                })
            }
        },
        // 执行分享
        share() {
            const data = this.user
            const that = this
			const link = location.href.split('#')[0]
			const title = `${data.name}的工品主页`
            const dynamic = `${data.signature}`
            const imgUrl = 'https://www.mrobiji.com/images/share-user-index.jpg'
            customShare({
				shareData: {
					shareDynamic: {
						title: `${title}${dynamic ? ` | ${dynamic}` : ''}`,
						link,
						imgUrl,
						desc: `${dynamic}`,
					},
					shareFriend: {
						title,
						link,
						imgUrl,
						desc: `${dynamic}`,
					}
				},
				fn() {
					
				}
			})
        }
    },
    mounted() {
        const that = this
        checkCacheaIsPageData({
            sessionStorageKey: 'UserIndexListCache',
            pageQueryStr: this.$route.query,
            callback(data) {
                if (data) {
                    that.setPageCacheData(data)
                    sessionStorage.removeItem('UserIndexListCache')
                    that.canClear = false
                } else {
                    that.canClear = true
                }
            }
        })
    },
    activated() {
        this.getData()
        this.checkClear()
        document.getElementById(this.activeListOpt).scrollTop = this.$route.meta.listScrollTop
    },
	beforeRouteLeave (to, from, next) {
		from.meta.listScrollTop = document.getElementById(this.activeListOpt).scrollTop
		next()
	},
    components: {
        Top,
        TopNav,
        UserMenu,
        List,
        OptSelectSti,
    }
}
</script>

<style lang="scss" scoped>
.vist-sti-icon {
    margin-right: 2px;
}

.vist-sti-count {
    font-size: 12px;
    padding-right: 3px;
}
</style>